package com.tanhua.dubbo.api.Impl;

import com.itheima.dubbo.api.UserLikeApi;
import com.tanhua.model.domain.UserLike;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

/**
 * @Author Pan Rundong
 * @Date 2023-03-05 22:49
 * @Desc userLike表接口实现类
 */
@DubboService
public class UserLikeApiImpl implements UserLikeApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 储存或更新用户信息
     *
     * @param userId
     * @param likeUserId
     * @return java.lang.Boolean
     * @Author Pan Rundong
     */
    @Override
    public Boolean saveOrUpdate(Long userId, Long likeUserId, Boolean isLike) {
        try {
            //1.查询用户信息
            Query query = Query.query(Criteria.where("userId").is(userId).
                    and("likeUserId").is(likeUserId));
            if (mongoTemplate.exists(query, UserLike.class)) {
                //1.1 不存在，保存
                UserLike userLike = new UserLike();
                userLike.setUserId(userId);
                userLike.setLikeUserId(likeUserId);
                userLike.setCreated(System.currentTimeMillis());
                userLike.setUpdated(System.currentTimeMillis());
                userLike.setIsLike(isLike);
            } else {
                //1.2 更新
                Update update = Update.update("isLike", isLike)
                        .set("updated",System.currentTimeMillis());
                mongoTemplate.updateFirst(query,update,UserLike.class);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
